<template>
  <div class="md-page-container">
    <!-- 左侧目录区域 -->
    <div class="sidebar" :class="{ collapsed: sidebarCollapsed }">
      <div class="sidebar-header">
        <a-button
          type="text"
          :icon="h(MenuFoldOutlined)"
          @click="toggleSidebar"
          class="collapse-btn"
        />
      </div>

      <div class="toc-container">
        <div v-if="!sidebarCollapsed && tocData.length > 0" class="toc-list">
          <div
            v-for="item in tocData"
            :key="item.id"
            :class="['toc-item', `level-${item.level}`, { active: activeHeading === item.id }]"
            @click="scrollToHeading(item.id)"
          >
            <span class="toc-text">{{ item.text }}</span>
          </div>
        </div>

        <div v-if="!sidebarCollapsed && tocData.length === 0" class="empty-toc">
          <a-empty description="暂无目录结构" />
        </div>
      </div>
    </div>

    <!-- 展开按钮（固定在左上角，仅在折叠时显示） -->
    <a-button
      v-if="sidebarCollapsed"
      type="text"
      @click="toggleSidebar"
      class="expand-btn-fixed"
      shape="circle"
    >
      <template #icon>
        <MenuUnfoldOutlined />
      </template>
    </a-button>

    <!-- 操作按钮（固定在右上角） -->
    <a-dropdown placement="bottomRight" trigger="click">
      <a-button type="text" class="actions-btn-fixed" shape="circle">
        <template #icon>
          <DownOutlined />
        </template>
      </a-button>
      <template #overlay>
        <a-menu>
          <a-menu-item key="download" @click="downloadMarkdown">
            <template #icon>
              <DownloadOutlined />
            </template>
            下载
          </a-menu-item>
          <a-menu-item key="print" @click="printDocument">
            <template #icon>
              <PrinterOutlined />
            </template>
            打印
          </a-menu-item>
          <a-menu-item key="fullscreen" @click="toggleFullscreen">
            <template #icon>
              <FullscreenOutlined />
            </template>
            全屏
          </a-menu-item>
        </a-menu>
      </template>
    </a-dropdown>

    <!-- 右侧内容区域 -->
    <div class="content-area" :class="{ 'sidebar-collapsed': sidebarCollapsed }">
      <!-- Markdown 编辑器预览模式 -->
      <div class="markdown-container" ref="markdownContainer">
        <div v-if="loading" class="loading-container">
          <a-spin size="large" tip="加载中..." />
        </div>

        <div v-else-if="markdownContent" class="preview-container">
          <MdPreview
            :model-value="markdownContent"
            :preview-theme="previewTheme"
            :code-theme="codeTheme"
            @on-get-catalog="onGetCatalog"
            class="md-preview"
          />
        </div>

        <div v-else class="empty-content">
          <a-empty description="暂无文档内容">
            <template #image>
              <FileTextOutlined style="font-size: 64px; color: #d9d9d9" />
            </template>
            <a-button type="primary" @click="fetchData"> 加载示例文档 </a-button>
          </a-empty>
        </div>
      </div>
    </div>
    <ToTop></ToTop>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, h } from 'vue'
import { message } from 'ant-design-vue'
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  DownOutlined,
  DownloadOutlined,
  PrinterOutlined,
  FileTextOutlined,
  FullscreenOutlined,
} from '@ant-design/icons-vue'
import { MdPreview } from 'md-editor-v3'
import 'md-editor-v3/lib/preview.css'
import ToTop from '@/components/ToTop.vue'
import { getGenerateTeachVo } from '@/api/generateTeachController'
import { useRoute } from 'vue-router'
const route = useRoute()
// 响应式数据
const sidebarCollapsed = ref(false)
const loading = ref(false)
const markdownContent = ref('')
const markdownContainer = ref<HTMLElement>()
const activeHeading = ref('')
//id : 1947574294777569281

// 导入方式2：整体导入
import ShareUtil from '@/utils/share'


const loadShareData = async () => {
  const data = await ShareUtil.verifyAndLoadData(route)
  if (data) {
    currentDoc.value.title = data.data.data?.title ?? ''
    currentDoc.value.content = data.data.data?.content ?? ''
    currentDoc.value.lastModified = data.data.data?.editTime ?? ''
    markdownContent.value = data.data.data?.content ?? ''
    console.log('加载的数据:', data.data.data )
  }
}


const currentDoc = ref({
  title: '',
  content: '',
  lastModified: '',
})
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getGenerateTeachVo({
      id: '1947574294777569281',
    })
    if (res.data.data && res.data.code === 0) {
      currentDoc.value.title = res.data.data.title ?? ''
      currentDoc.value.content = res.data.data.content ?? ''
      currentDoc.value.lastModified = res.data.data?.editTime ?? ''
      markdownContent.value = res.data.data.content ?? ''
      message.success('文档加载成功')
    }
  } catch (error) {
    message.error('加载文档失败')
    console.error('Load document error:', error)
  } finally {
    loading.value = false
  }
}

// 目录数据
const tocData = ref<any[]>([])

// 编辑器主题配置
const previewTheme = ref('default')
const codeTheme = ref('atom')

// 切换侧边栏
const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

// 滚动到指定标题
const scrollToHeading = (headingId: string) => {
  const element = document.getElementById(headingId)
  if (element) {
    element.scrollIntoView({
      behavior: 'smooth',
      block: 'start',
    })
    // 设置当前活跃的标题
    activeHeading.value = headingId
  }
}

// 获取目录回调（md-editor-v3提供）
const onGetCatalog = (list: any[]) => {
  tocData.value = list.map((item, index) => ({
    id: `heading-${index}`,
    text: item.text,
    level: item.level,
    anchor: item.anchor,
  }))
}

// 全屏切换
const toggleFullscreen = () => {
  if (!document.fullscreenElement) {
    markdownContainer.value?.requestFullscreen()
  } else {
    document.exitFullscreen()
  }
}

// 下载 Markdown
const downloadMarkdown = () => {
  if (!markdownContent.value) {
    message.warning('暂无内容可下载')
    return
  }

  const blob = new Blob([markdownContent.value], { type: 'text/markdown' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${currentDoc.value.title || 'document'}.md`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)

  message.success('文档下载成功')
}

// 打印文档
const printDocument = () => {
  if (!markdownContent.value) {
    message.warning('暂无内容可打印')
    return
  }

  // 获取预览区域的HTML内容
  const previewElement = document.querySelector('.md-preview .md-preview-wrapper')
  if (!previewElement) {
    message.warning('无法获取预览内容')
    return
  }

  const printWindow = window.open('', '_blank')
  if (printWindow) {
    const printContent = `
      <html>
        <head>
          <title>${currentDoc.value.title}</title>
          <style>
            body {
              font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
              line-height: 1.6;
              color: #333;
              max-width: 800px;
              margin: 0 auto;
              padding: 20px;
            }
            h1, h2, h3, h4, h5, h6 {
              color: #333;
              margin-top: 24px;
              margin-bottom: 16px;
            }
            p { line-height: 1.6; margin-bottom: 16px; }
            code {
              background: #f6f8fa;
              padding: 2px 4px;
              border-radius: 3px;
              font-family: Monaco, Menlo, monospace;
            }
            pre {
              background: #f6f8fa;
              padding: 16px;
              border-radius: 6px;
              overflow-x: auto;
              margin: 16px 0;
            }
            blockquote {
              border-left: 4px solid #dfe2e5;
              padding-left: 16px;
              margin: 16px 0;
              color: #666;
            }
            table {
              border-collapse: collapse;
              width: 100%;
              margin: 16px 0;
            }
            th, td {
              border: 1px solid #dfe2e5;
              padding: 8px 12px;
              text-align: left;
            }
            th {
              background: #f6f8fa;
              font-weight: 600;
            }
            img { max-width: 100%; height: auto; }
          </style>
        </head>
        <body>
          <h1>${currentDoc.value.title}</h1>
          ${previewElement.innerHTML}
        </body>
      </html>
    `
    printWindow.document.write(printContent)
    printWindow.document.close()
    printWindow.print()
  }
}

// 组件挂载时的初始化
onMounted(() => {
  loadShareData()
  // 可以在这里加载默认文档或从 API 获取文档列表
  // fetchData()
})
</script>

<style scoped>
.md-page-container {
  display: flex;
  min-height: calc(100vh - 85px);
  background: #fafbfc;
  padding: 0;
}

/* 左侧边栏 */
.sidebar {
  width: 280px;
  background: white;
  border-right: 1px solid #e1e4e8;
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
  z-index: 100;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.06);
  position: fixed;
  top: 125px;
  left: 40px;
  height: calc(100vh - 200px);
  overflow: hidden;
  border-radius: 12px;
}

.sidebar.collapsed {
  width: 0;
  overflow: hidden;
}

.sidebar-header {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #e1e4e8;
  background: #f8f9fa;
}

.collapse-btn {
  color: #586069;
  border: none;
  background: none;
}

.collapse-btn:hover {
  color: #0366d6;
  background: rgba(3, 102, 214, 0.1);
}

/* 固定展开按钮（左上角） */
.expand-btn-fixed {
  position: fixed;
  top: 125px;
  left: 5px;
  z-index: 101;
  background: white;
  border: 1px solid #e1e4e8;
  border-radius: 50% !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  color: #586069;
  padding: 5px 8px;
  font-weight: 500;
}

.expand-btn-fixed:hover {
  color: #0366d6;
  border-color: #0366d6;
  background: rgba(3, 102, 214, 0.05);
}

/* 固定在右上角的圆形操作按钮 */
.actions-btn-fixed {
  position: fixed;
  top: 125px;
  right: 40px;
  z-index: 101;
  background: white;
  border: 1px solid #e1e4e8;
  border-radius: 50% !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  color: #586069;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 !important;
}

.actions-btn-fixed:hover {
  color: #0366d6;
  border-color: #0366d6;
  background: rgba(3, 102, 214, 0.05);
  transform: scale(1.05);
  transition: all 0.2s ease;
}

.toc-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px 0;
}

.toc-list {
  padding: 0 20px;
}

.toc-item {
  padding: 10px 16px;
  margin: 4px 0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
  line-height: 1.6;
  border-left: 3px solid transparent;
  position: relative;
}

.toc-item:hover {
  background: #f1f8ff;
  color: #0366d6;
  transform: translateX(2px);
}

.toc-item.active {
  background: #e1f5fe;
  color: #0366d6;
  border-left-color: #0366d6;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(3, 102, 214, 0.1);
}

.toc-item.level-1 {
  font-weight: 600;
  color: #24292e;
  margin-left: 0;
  font-size: 15px;
}

.toc-item.level-2 {
  font-weight: 500;
  color: #586069;
  margin-left: 20px;
}

.toc-item.level-3 {
  color: #6a737d;
  margin-left: 40px;
}

.toc-item.level-4 {
  color: #959da5;
  margin-left: 60px;
  font-size: 13px;
}

.toc-item.level-5,
.toc-item.level-6 {
  color: #c6cbd1;
  margin-left: 80px;
  font-size: 13px;
}

.toc-text {
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.empty-toc {
  padding: 60px 20px;
  text-align: center;
  color: #6a737d;
}

/* 右侧内容区域 */
.content-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fafbfc;
  transition: all 0.3s ease;
  margin-left: 360px;
  min-height: calc(100vh - 85px);
}

.content-area.sidebar-collapsed {
  margin-left: 0;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 40px;
  background: white;
  border-bottom: 1px solid #e1e4e8;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  z-index: 5;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.document-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #24292e;
}

/* Markdown 内容区域 */
.markdown-container {
  flex: 1;
  overflow-y: auto;
  position: relative;
  padding: 40px;
  display: flex;
  justify-content: center;
  height: calc(100vh - 85px - 80px); /* 减去header高度和padding */
}

.preview-container {
  width: 100%;
  max-width: 900px;
  background: #fafbfc;
  border-radius: 0;
  box-shadow: none;
  border: none;
  overflow: visible;
}

.md-preview {
  height: auto !important;
  border: none !important;
  background: #fafbfc !important;
  border-radius: 0 !important;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
  background: #fafbfc;
  border-radius: 0;
  box-shadow: none;
}

.empty-content {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 500px;
  background: #fafbfc;
  border-radius: 0;
  box-shadow: none;
}

/* md-preview 样式覆盖 */
:deep(.md-preview .md-preview-wrapper) {
  padding: 48px 56px !important;
  font-size: 16px !important;
  line-height: 1.8 !important;
  color: #24292e !important;
  background: #fafbfc !important;
  font-family:
    -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Noto Sans', Helvetica, Arial, sans-serif !important;
}

:deep(.md-preview h1) {
  font-size: 32px !important;
  font-weight: 600 !important;
  color: #24292e !important;
  border-bottom: 1px solid #e1e4e8 !important;
  padding-bottom: 16px !important;
  margin: 32px 0 24px 0 !important;
}

:deep(.md-preview h2) {
  font-size: 24px !important;
  font-weight: 600 !important;
  color: #24292e !important;
  border-bottom: 1px solid #e1e4e8 !important;
  padding-bottom: 12px !important;
  margin: 28px 0 20px 0 !important;
}

:deep(.md-preview h3) {
  font-size: 20px !important;
  font-weight: 600 !important;
  color: #24292e !important;
  margin: 24px 0 16px 0 !important;
}

:deep(.md-preview h4) {
  font-size: 18px !important;
  font-weight: 600 !important;
  color: #24292e !important;
  margin: 20px 0 12px 0 !important;
}

:deep(.md-preview h5),
:deep(.md-preview h6) {
  font-size: 16px !important;
  font-weight: 600 !important;
  color: #24292e !important;
  margin: 16px 0 8px 0 !important;
}

:deep(.md-preview p) {
  margin: 16px 0 !important;
  line-height: 1.8 !important;
  color: #24292e !important;
}

:deep(.md-preview blockquote) {
  border-left: 4px solid #0366d6 !important;
  background: white !important;
  padding: 16px 24px !important;
  margin: 20px 0 !important;
  border-radius: 6px !important;
  color: #586069 !important;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1) !important;
}

:deep(.md-preview ul),
:deep(.md-preview ol) {
  margin: 16px 0 !important;
  padding-left: 32px !important;
}

:deep(.md-preview li) {
  margin: 8px 0 !important;
  line-height: 1.8 !important;
  color: #24292e !important;
}

:deep(.md-preview table) {
  border-radius: 8px !important;
  overflow: hidden !important;
  border: 1px solid #e1e4e8 !important;
  margin: 20px 0 !important;
  width: 100% !important;
  border-collapse: collapse !important;
  background: white !important;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1) !important;
}

:deep(.md-preview th) {
  background: #f6f8fa !important;
  padding: 12px 16px !important;
  font-weight: 600 !important;
  color: #24292e !important;
  border: 1px solid #e1e4e8 !important;
}

:deep(.md-preview td) {
  padding: 12px 16px !important;
  border: 1px solid #e1e4e8 !important;
  color: #24292e !important;
  background: white !important;
}

:deep(.md-preview code) {
  background: white !important;
  color: #e36209 !important;
  padding: 4px 8px !important;
  border-radius: 6px !important;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace !important;
  font-size: 14px !important;
  border: 1px solid #e1e4e8 !important;
}

:deep(.md-preview pre) {
  background: white !important;
  border-radius: 8px !important;
  border: 1px solid #e1e4e8 !important;
  padding: 20px !important;
  margin: 20px 0 !important;
  overflow-x: auto !important;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1) !important;
}

:deep(.md-preview pre code) {
  background: none !important;
  color: #24292e !important;
  padding: 0 !important;
  border-radius: 0 !important;
  border: none !important;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .markdown-container {
    padding: 24px;
  }

  :deep(.md-preview .md-preview-wrapper) {
    padding: 32px 40px !important;
  }
}

@media (max-width: 768px) {
  .md-page-container {
    flex-direction: column;
  }

  .sidebar {
    width: 100% !important;
    height: 240px;
    border-right: none;
    border-bottom: 1px solid #e1e4e8;
    position: relative !important;
    top: auto !important;
    left: auto !important;
    height: 240px !important;
  }

  .sidebar.collapsed {
    height: 0;
  }

  .content-area {
    margin-left: 0 !important;
  }

  .content-header {
    padding: 16px 20px;
  }

  .document-title {
    font-size: 20px;
  }

  .markdown-container {
    padding: 20px 16px;
  }

  .preview-container {
    max-width: 100%;
    border-radius: 0;
  }

  :deep(.md-preview .md-preview-wrapper) {
    padding: 24px 20px !important;
    font-size: 15px !important;
  }

  :deep(.md-preview h1) {
    font-size: 26px !important;
  }

  :deep(.md-preview h2) {
    font-size: 22px !important;
  }
}

/* 滚动条样式 */
.toc-container::-webkit-scrollbar,
.preview-container::-webkit-scrollbar {
  width: 8px;
}

.toc-container::-webkit-scrollbar-track,
.preview-container::-webkit-scrollbar-track {
  background: #f6f8fa;
  border-radius: 4px;
}

.toc-container::-webkit-scrollbar-thumb,
.preview-container::-webkit-scrollbar-thumb {
  background: #d1d5da;
  border-radius: 4px;
}

.toc-container::-webkit-scrollbar-thumb:hover,
.preview-container::-webkit-scrollbar-thumb:hover {
  background: #959da5;
}

/* 全屏模式样式 */
.markdown-container:fullscreen {
  background: #fafbfc;
  padding: 40px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.markdown-container:fullscreen .preview-container {
  max-width: 1000px;
  height: calc(100vh - 80px);
  overflow-y: auto;
}

.markdown-container:fullscreen .md-preview {
  height: auto !important;
}

/* 动画效果 */
.toc-item,
.preview-container,
.sidebar,
.content-area {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.toc-item:hover {
  transform: translateX(4px);
}

/* 阴影效果 */
</style>
